package org.vaadin.vaadinjit.widgetset.client.ui;

import java.util.LinkedHashMap;
import java.util.Map;

import com.google.gwt.core.client.JavaScriptObject;

/**
 * This class contains a set of static methods used by JIT to make callbacks 
 * into GWT. Instances of type VJitWidget registers themselves with this
 * class to receive callbacks from JIT.
 * 
 * 
 * @author jonkka
 *
 */
public class JitWrapper {

	private static Map<String, VJitWidget<?>> widgetMap;
	
	static {
		widgetMap = new LinkedHashMap<String, VJitWidget<?>>();
		exportToJit();
	}

	
	/**
	 * Register a widget with the wrapper.
	 * 
	 * @param jitWidget the widget
	 */
	public static void registerJitWidget(VJitWidget<?> jitWidget) {
		widgetMap.put(jitWidget.getJitIdentifier(), jitWidget);
	}
	
	private static VJitWidget<?> getJitWidget(String id) {
		VJitWidget<?> widget = widgetMap.get(id);
		if (widget == null)
			throw new RuntimeException("Invalid id '" + id + "' passed ti JitWrapper");
		
		return widget;
	}
	
	
	/**
	 * Fired when the mouse is moved over a label in a Chart.
	 * 
	 * @param id
	 * @param label
	 */
	public static void fireChartHoverLabel(String id, String stack) {
		VJitWidget<?> widget = getJitWidget(id);
		
		if (widget instanceof VJitChartWidget) {
			((VJitChartWidget<?>) widget).onHoverLabel(stack);
		}	
	}
	
	
	public static void fireAreaChartClick(String id, JavaScriptObject event, String stack)  {
		VJitWidget<?> widget = getJitWidget(id);
		
		if (widget instanceof VJitAreaChart) {
			((VJitAreaChart) widget).onClickStack(stack);
		}
	}
	
	
	public static void fireSpaceTreeClick(String id, String nodeId) {
		VJitWidget<?> widget = getJitWidget(id);
		
		if (widget instanceof VJitSpaceTree) {
			((VJitSpaceTree) widget).onClickNode(nodeId);
		}
	}


	/**
	 * Makes the methods accessible from JIT by exporting them to $wnd.$jit
	 */
	private static native void exportToJit() /*-{
		$wnd.$jit.fireChartHoverLabel = 
			@org.vaadin.vaadinjit.widgetset.client.ui.JitWrapper::fireChartHoverLabel(Ljava/lang/String;Ljava/lang/String;);
		$wnd.$jit.fireAreaChartClick =  
			@org.vaadin.vaadinjit.widgetset.client.ui.JitWrapper::fireAreaChartClick(Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;Ljava/lang/String;);
		$wnd.$jit.fireSpaceTreeClick =
			@org.vaadin.vaadinjit.widgetset.client.ui.JitWrapper::fireSpaceTreeClick(Ljava/lang/String;Ljava/lang/String;);

	}-*/;
	
}
